package org.jetnuke.modules.admin.modules;

import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.n3.nanoxml.IXMLParser;
import net.n3.nanoxml.IXMLReader;
import net.n3.nanoxml.StdXMLReader;
import net.n3.nanoxml.XMLParserFactory;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.Configuration;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.util.GetResources;

public class AddModule implements IAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(AddModule.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jetnuke.common.IAction#exec(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse,
	 *      org.apache.velocity.VelocityContext, org.jetnuke.common.IModuleInfo,
	 *      java.lang.String, org.jetnuke.common.IUserInfo,
	 *      org.jetnuke.common.IAdminInfo)
	 */
	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - start"); //$NON-NLS-1$
		}

		List toAddList = new ArrayList();
		List errorList = new ArrayList();

		try {
			ServletContext sc = request.getSession(true).getServletContext();
			Configuration cfg = (Configuration) sc.getAttribute("_cfg");
			List modulesFS = GetResources.getDirectories(sc,
					"/modules/");
			modulesFS.remove("admin");
			Set modulesPathDB = cfg.modules.keySet();
			Iterator it = modulesFS.iterator();

			while (it.hasNext()) {
				String fileModuleName = (String) it.next();
				// String pathToFind=fileModuleName;
				// Iterator it2=modulesPathDB.iterator();
				boolean found = false;
				if (modulesPathDB.contains(fileModuleName))
					found = true;
				/*
				 * while(it2.hasNext()){ IBlockInfo
				 * bInfo=(IBlockInfo)it2.next();
				 * if(bInfo.getPath().equals(pathToFind)){ found=true; break; }
				 *  }
				 */
				if (!found) {

					try {
						File f = new File(sc.getRealPath("")
								+ "/modules/" + fileModuleName
								+ "/config.xml");
						StringBuffer buf = readFile(f);
						IXMLParser parser = XMLParserFactory
								.createDefaultXMLParser();
						IXMLReader reader = StdXMLReader.stringReader(buf
								.toString());
						parser.setReader(reader);
						parser.parse();
						toAddList.add(fileModuleName);
					} catch (Throwable e1) {
						logger
								.error(
										"exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo)", e1); //$NON-NLS-1$

						errorList.add(fileModuleName);
					}

					// System.out.println(fileBlockName);
				}
			}

		} catch (Throwable e) {
			logger
					.warn(
							"exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - exception ignored", e); //$NON-NLS-1$
		}
		vc.put("list", toAddList);
		vc.put("errorList", errorList);
		ActionForward returnActionForward = new ActionForward(op, info);
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
		}
		return returnActionForward;
	}

	private StringBuffer readFile(File f) {
		if (logger.isDebugEnabled()) {
			logger.debug("readFile(File) - start"); //$NON-NLS-1$
		}

		StringBuffer buf = new StringBuffer(1000);
		try {
			BufferedReader in = new BufferedReader(new FileReader(f));
			String str;
			while ((str = in.readLine()) != null) {
				buf.append(str);
			}
			in.close();
		} catch (IOException e) {
			logger.warn("readFile(File) - exception ignored", e); //$NON-NLS-1$
		}

		if (logger.isDebugEnabled()) {
			logger.debug("readFile(File) - end"); //$NON-NLS-1$
		}
		return buf;
	}
}
